package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.constant.MessageConst;
import com.itheima.dao.MemberDao;
import com.itheima.dao.OrderDao;
import com.itheima.dao.OrderSettingDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderSetting;
import org.springframework.beans.factory.annotation.Autowired;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

@Service
public class OrderServiceimpl implements OrderService {
    @Autowired
    OrderSettingDao orderSettingDao;
    @Autowired
    MemberDao memberDao;
    @Autowired
    OrderDao orderDao;
    @Override
    public Result addOrder(Map<String, String> map) throws Exception {
        String orderDate = map.get("orderDate");
        Date date = new SimpleDateFormat("yyyy-MM-dd").parse(orderDate);
        OrderSetting orderSetting = orderSettingDao.findByDate(date);
        String telephone = map.get("telephone");
        String setmealId = map.get("setmealId");
        if (orderSetting==null){
            return new Result(false, MessageConst.GET_ORDERSETTING_FAIL);
        }
        if (orderSetting.getReservations()>=orderSetting.getNumber()){
            return new Result(false,MessageConst.ORDER_FULL);
        }
        Member member=memberDao.findByTelephone(telephone);
        if (member==null){
           member=new Member();
           member.setName(map.get("name"));
           member.setSex(map.get("sex"));
           member.setIdCard(map.get("idCard"));
           member.setPhoneNumber(telephone);
           member.setRegTime(new Date());
           memberDao.addMember(member);
        }else {
            Order order=new Order();
           order.setMemberId(member.getId());
           order.setOrderDate(date);
           order.setSetmealId(Integer.valueOf(setmealId));
          Long count= orderDao.findByOrder(order);
          if (count>0){
             return new Result(false,MessageConst.HAS_ORDERED);
          }

        }
        Order order=new Order();
        order.setMemberId(member.getId());
        order.setOrderDate(date);
        order.setOrderType(map.get("orderType"));
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setSetmealId(Integer.valueOf(setmealId));

        orderDao.addOrder(order);
        orderSetting.setReservations(orderSetting.getReservations()+1);
        orderSettingDao.update(orderSetting);

        return new Result(true,MessageConst.ORDER_SUCCESS,order);
    }

    @Override
    public Map<String, Object> findById(Integer id) {
        return orderDao.findById(id);
    }
}
